package com.mlink.ai.chat.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Process
import android.util.TypedValue
import android.widget.Toast
import androidx.annotation.ArrayRes
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.constants.MYSELF_URL_IN_GOOGLE_PLAY
import java.util.*

fun Int.dp2px() = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    AiChatApplication.app.resources.displayMetrics
).toInt()

internal fun Context.searchMyselfOnPlayStore() {
    openUrl(MYSELF_URL_IN_GOOGLE_PLAY)
}

/**
 * 浏览器打开该链接。
 * @param url 待打开的url。
 */
internal fun Context.openUrl(url: String) {
    val intent = Intent(Intent.ACTION_VIEW)
        .setData(Uri.parse(url))
    if (this !is Activity) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    try {
        this.startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
    }
}

internal fun Fragment.openUrl(url: String) {
    val intent = Intent(Intent.ACTION_VIEW)
        .setData(Uri.parse(url))
    if (this !is Activity) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    try {
        this.startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
    }
}


fun Context.shareText(text: String) {
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.type = "text/plain"
    shareIntent.putExtra(Intent.EXTRA_TEXT, text)
    try {
        startActivity(Intent.createChooser(shareIntent, "Share with"))
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(this, "No application found to handle this request", Toast.LENGTH_SHORT)
            .show()
    }
}

fun Fragment.shareText(text: String) {
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.type = "text/plain"
    shareIntent.putExtra(Intent.EXTRA_TEXT, text)
    try {
        startActivity(Intent.createChooser(shareIntent, "Share with"))
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(context, "No application found to handle this request", Toast.LENGTH_SHORT)
            .show()
    }
}
fun Context.getStatusBarHeight(): Int {
    val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
    return if (resourceId > 0) {
        resources.getDimensionPixelSize(resourceId)
    } else {
        0
    }
}

fun Context.subStringSafely(string: String?, startIndex: Int, endIndex: Int): String? {
    if (string.isNullOrEmpty() || string.length < endIndex) {
        return string
    }
    return string.substring(startIndex, endIndex)
}

fun Context.getArrayIdentifier(resourceName: String) = resources.getIdentifier(
    resourceName,
    "array",
    packageName
)

fun Context.isServiceRunning(cls: Class<*>): Boolean {
    val componentName = ComponentName(this, cls)
    val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    var isRunning = false
    try {
        val runningServiceInfoList =
            activityManager.getRunningServices(Int.MAX_VALUE) as? List<ActivityManager.RunningServiceInfo>
                ?: return false
        for (info in runningServiceInfoList) {
            if (info.service == componentName) {
                if (info.pid == Process.myPid()) {
                    isRunning = true
                }
            }
        }
    } catch (e: Exception) {
        isRunning = false
    }
    return isRunning
}


fun Context.getEnglishString(@StringRes resId: Int): String {
    val configurationContext = createConfigurationContext(Configuration(resources!!.configuration).apply { setLocale(Locale("en")) })
    return configurationContext.resources.getString(resId)
}

fun Context.getEnglishStringArray(@ArrayRes resId: Int): Array<String> {
    val configurationContext = createConfigurationContext(Configuration(resources!!.configuration).apply { setLocale(Locale("en")) })
    return configurationContext.resources.getStringArray(resId)
}

private const val PLAY_STORE_SUBSCRIPTION_DEEPLINK_URL =
    "https://play.google.com/store/account/subscriptions?sku=%s&package=%s"

fun Context.manageSubscription(sku: String) {
    val intent = Intent(Intent.ACTION_VIEW)
    val url = String.format(PLAY_STORE_SUBSCRIPTION_DEEPLINK_URL, sku, packageName)
    intent.data = Uri.parse(url)
    if (this !is Activity) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    try {
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // catch ActivityNotFoundException
    }
}
